<template>
  <div class="delivery-dashboard">
    <h1>配送员仪表盘</h1>
    
    <!-- 欢迎信息 -->
    <el-card class="welcome-card">
      <h2>欢迎回来，{{ userStore.name }}</h2>
      <p>今天是 {{ currentDate }}，祝您工作顺利！</p>
    </el-card>
    
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <template #header>
            <div class="card-header">
              <span>待配送任务</span>
            </div>
          </template>
          <div class="stat-value">{{ stats.pendingTasks }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <template #header>
            <div class="card-header">
              <span>配送中任务</span>
            </div>
          </template>
          <div class="stat-value">{{ stats.deliveringTasks }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <template #header>
            <div class="card-header">
              <span>今日已完成</span>
            </div>
          </template>
          <div class="stat-value">{{ stats.completedToday }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <template #header>
            <div class="card-header">
              <span>平均配送时间</span>
            </div>
          </template>
          <div class="stat-value">{{ stats.avgDeliveryTime || '--' }}</div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 待处理任务列表 -->
    <el-card class="tasks-card">
      <template #header>
        <div class="card-header">
          <span>待处理任务</span>
          <el-button type="primary" size="small" @click="goToTasksPage">查看全部</el-button>
        </div>
      </template>
      <el-table :data="pendingTasks" style="width: 100%">
        <el-table-column prop="delivery_number" label="配送编号" width="120" />
        <el-table-column prop="order_number" label="订单编号" width="120" />
        <el-table-column prop="customer_name" label="客户名称" width="120" />
        <el-table-column prop="address" label="配送地址" min-width="200" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityType(row.priority)">{{ getPriorityText(row.priority) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              link 
              size="small"
              :style="{ color: '#ffffff', backgroundColor: '#409EFF', padding: '2px 6px', borderRadius: '4px' }"
              @click="handleUpdateStatus(row)"
            >更新状态</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 更新状态对话框 -->
    <el-dialog v-model="statusDialogVisible" title="更新配送状态" width="500px">
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusType(currentTask.status)">{{ getStatusText(currentTask.status) }}</el-tag>
        </el-form-item>
        <el-form-item label="新状态">
          <el-select v-model="statusForm.status" placeholder="请选择新状态">
            <el-option v-for="option in statusOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="statusForm.remarks" type="textarea" rows="3"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="statusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitStatusUpdate">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getDeliveryTasks, updateDeliveryTaskStatus, getDeliverymanDashboard } from '@/api/delivery'
import { useUserStore } from '@/stores/user'
import { getToken } from '@/utils/auth'
import axios from 'axios'

const router = useRouter()
const userStore = useUserStore()

// 当前日期
const currentDate = computed(() => {
  const date = new Date()
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
})

// 统计数据
const stats = reactive({
  pendingTasks: 0,
  completedToday: 0,
  deliveringTasks: 0,
  avgDeliveryTime: 0
})

// 待处理任务列表
const pendingTasks = ref([])

// 获取仪表盘数据
const fetchDashboardData = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    // 获取配送任务列表
    const params = {
      page: 1,
      page_size: 10
    }
    
    // 如果是配送员角色，添加配送员ID作为筛选条件
    if (userStore.role === 'deliveryman' && userStore.user && userStore.user.id) {
      params.deliveryman = userStore.user.id
    }
    
    console.log('发送查询参数:', params)
    const response = await getDeliveryTasks(params)
    
    console.log('API响应数据:', response)
    
    if (response && response.data && response.data.code === 200 && response.data.data) {
      const tasks = response.data.data.items || []
      
      // 计算统计数据
      stats.pendingTasks = tasks.filter(task => task.status === 'assigned').length
      stats.deliveringTasks = tasks.filter(task => task.status === 'delivering').length
      stats.completedToday = tasks.filter(task => 
        task.status === 'completed' && 
        new Date(task.actual_delivery_time).toDateString() === new Date().toDateString()
      ).length
      
      // 计算平均配送时间（如果有完成的任务）
      const completedTasks = tasks.filter(task => task.status === 'completed' && task.actual_delivery_time)
      if (completedTasks.length > 0) {
        let totalMinutes = 0
        let validTaskCount = 0
        
        completedTasks.forEach(task => {
          // 查找最后一次 'delivering' 状态记录的时间
          const deliveringRecord = task.status_records
            ?.filter(record => record.status === 'delivering')
            ?.sort((a, b) => new Date(b.created_at) - new Date(a.created_at))[0]
            
          if (deliveringRecord && task.actual_delivery_time) {
            const startTime = new Date(deliveringRecord.created_at)
            const endTime = new Date(task.actual_delivery_time)
            const diffMinutes = Math.round((endTime - startTime) / (1000 * 60))
            if (diffMinutes > 0) {
              totalMinutes += diffMinutes
              validTaskCount++
            }
          }
        })
        
        if (validTaskCount > 0) {
          const avgMinutes = Math.round(totalMinutes / validTaskCount)
          const hours = Math.floor(avgMinutes / 60)
          const minutes = avgMinutes % 60
          stats.avgDeliveryTime = hours > 0 ? `${hours}小时${minutes}分钟` : `${minutes}分钟`
        } else {
          stats.avgDeliveryTime = '--'
        }
      } else {
        stats.avgDeliveryTime = '--'
      }
      
      // 获取待处理任务（已分配和配送中的任务）
      pendingTasks.value = tasks.filter(task => 
        task.status === 'assigned' || task.status === 'delivering'
      ).slice(0, 5) // 只显示前5条
    } else {
      ElMessage.error(response?.data?.message || '获取仪表盘数据失败')
    }
  } catch (error) {
    console.error('获取仪表盘数据失败:', error)
    ElMessage.error('获取仪表盘数据失败: ' + (error.response?.data?.detail || error.message))
  }
}

// 跳转到任务管理页面
const goToTasksPage = () => {
  router.push('/deliveryman/tasks')
}

// 状态更新对话框
const statusDialogVisible = ref(false)
const currentTask = reactive({
  id: null,
  status: ''
})
const statusForm = reactive({
  status: '',
  remarks: ''
})

// 状态选项
const statusOptions = computed(() => {
  if (currentTask.status === 'assigned') {
    return [
      { value: 'delivering', label: '开始配送' },
      { value: 'rejected', label: '拒绝任务' }
    ]
  } else if (currentTask.status === 'delivering') {
    return [
      { value: 'completed', label: '完成配送' }
    ]
  } else {
    return []
  }
})

// 处理更新状态
const handleUpdateStatus = (task) => {
  currentTask.id = task.id
  currentTask.status = task.status
  statusForm.status = ''
  statusForm.remarks = ''
  statusDialogVisible.value = true
}

// 提交状态更新
const submitStatusUpdate = async () => {
  if (!statusForm.status) {
    ElMessage.warning('请选择新状态')
    return
  }
  
  try {
    await updateDeliveryTaskStatus(currentTask.id, {
      status: statusForm.status,
      note: statusForm.remarks
    })
    
    ElMessage.success('状态更新成功')
    statusDialogVisible.value = false
    fetchDashboardData() // 刷新数据
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('更新状态失败: ' + (error.response?.data?.detail || error.message))
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'assigned': '已分配',
    'delivering': '配送中',
    'completed': '已完成',
  }
  return statusMap[status] || status
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'pending': 'info',
    'assigned': 'warning',
    'delivering': 'primary',
    'completed': 'success',
    'rejected': 'danger',
    'cancelled': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取优先级文本
const getPriorityText = (priority) => {
  const priorityMap = {
    'high': '高',
    'medium': '中',
    'low': '低'
  }
  return priorityMap[priority] || priority
}

// 获取优先级类型
const getPriorityType = (priority) => {
  const typeMap = {
    'high': 'danger',
    'medium': 'warning',
    'low': 'info'
  }
  return typeMap[priority] || 'info'
}

onMounted(() => {
  fetchDashboardData()
})
</script>

<style scoped>
.delivery-dashboard {
  padding: 20px;
}

.welcome-card {
  margin-bottom: 20px;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 140px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  text-align: center;
  color: var(--primary-color);
}

/* 为平均配送时间添加特殊样式 */
.stat-cards .el-col:nth-child(4) .stat-value {
  font-size: 18px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 0 10px;
  margin-top: 10px;
}

.tasks-card {
  margin-bottom: 20px;
}

.task-count {
  font-size: 32px;
  font-weight: bold;
  color: var(--primary-color);
}
</style>